<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html>
<head>
<title>Basic Swing components</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="Swing, basic components, Java, tutorial">
<meta name="description" content="This part of the Java Swing tutorial covers basic Swing components.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

</head>

<body>

<div class="container">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<div class="content">


<a href="/" title="Home">Home</a>&nbsp;
<a href=".." title="Home">Contents</a>


<h1>Basic Swing components</h1>


<p>
Swing components are basic building blocks of an application. Swing toolkit has 
a wide range of various widgets. Buttons, check boxes,sliders, list boxes etc.
Everything a programmer needs for his job. In this section of the tutorial, 
we will describe several useful components.
</p>

<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* NewSquare */
google_ad_slot = "0364418177";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script>



<h2>JLabel Component</h2>


<p>
<code>JLabel</code> is a simple component for displaying text, 
images or both. It does not react to input events.
</p>


<pre class="code">
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;

import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;


public class MyLabel extends JFrame {

    private Toolkit toolkit;

    public MyLabel() {

	setTitle("No Sleep");

        String lyrics =  "&lt;html&gt;It's way too late to think of&lt;br&gt;" + 
        "Someone I would call now&lt;br&gt;" + 
        "And neon signs got tired&lt;br&gt;" + 
        "Red eye flights help the stars out&lt;br&gt;" + 
        "I'm safe in a corner&lt;br&gt;" + 
        "Just hours before me&lt;br&gt;" + 
        "&lt;br&gt;" + 
        "I'm waking with the roaches&lt;br&gt;" + 
        "The world has surrendered&lt;br&gt;" + 
        "I'm dating ancient ghosts&lt;br&gt;" + 
        "The ones I made friends with&lt;br&gt;" + 
        "The comfort of fireflies&lt;br&gt;" + 
        "Long gone before daylight&lt;br&gt;" + 
        "&lt;br&gt;" + 
        "And if I had one wishful field tonight&lt;br&gt;" + 
        "I'd ask for the sun to never rise&lt;br&gt;" + 
        "If God leant his voice for me to speak&lt;br&gt;" + 
        "I'd say go to bed, world&lt;br&gt;" + 
        "&lt;br&gt;" + 
        "I've always been too late&lt;br&gt;" + 
        "To see what's before me&lt;br&gt;" + 
        "And I know nothing sweeter than&lt;br&gt;" + 
        "Champaign from last New Years&lt;br&gt;" + 
        "Sweet music in my ears&lt;br&gt;" + 
        "And a night full of no fears&lt;br&gt;" + 
        "&lt;br&gt;" + 
        "But if I had one wishful field tonight&lt;br&gt;" + 
        "I'd ask for the sun to never rise&lt;br&gt;" + 
        "If God passed a mic to me to speak&lt;br&gt;" + 
        "I'd say stay in bed, world&lt;br&gt;" + 
        "Sleep in peace&lt;/html&gt;";

        JPanel panel = new JPanel(); 
        panel.setLayout(new BorderLayout(10, 10));
 
        JLabel label = new JLabel(lyrics);
        label.setFont(new Font("Georgia", Font.PLAIN, 14));
        label.setForeground(new Color(50, 50, 25));


        panel.add(label, BorderLayout.CENTER);
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        add(panel);
        pack();

        toolkit = getToolkit();
        Dimension screensize = toolkit.getScreenSize();
        setLocation((screensize.width - getWidth())/2, 
            (screensize.height - getHeight())/2);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {

        MyLabel mylabel = new MyLabel();
        mylabel.setVisible(true);

    }
}
</pre>
<br>

<p>
In our example, we show lyrics of no sleep song from cardigans. We can use 
html tags in <code>JLabel</code> component.
We use the &lt;br&gt; tag to separate lines.
</p>

<pre class="explanation">
JPanel panel = new JPanel(); 
panel.setLayout(new BorderLayout(10, 10));
</pre>

<p>
We create a panel and set a <code>BorderLayout</code> manager.
</p>

<pre class="explanation">
JLabel label = new JLabel(lyrics);
label.setFont(new Font("Georgia", Font.PLAIN, 14));
label.setForeground(new Color(50, 50, 25));
</pre>

<p>
Here we create the label component. We set it's font to plain georgia, 
14 px tall. We also change the foreground color.
</p>

<pre class="explanation">
panel.add(label, BorderLayout.CENTER);
panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
</pre>

<p>
We put the label into the center of the panel. We put 10px around the label. 
</p>

<pre class="explanation">
 add(panel);
 pack();
</pre>

<p>
The panel is added to the frame component. We call the <code>pack()</code> method, 
which will resize the window, so that all components are visible.
</p>


<img src="/img/gui/javaswing/nosleep.jpg" alt="JLabel">
<div class="figure">Figure: JLabel</div>


<h2>JCheckBox</h2>

<p>
JCheckBox is a component that has two states. On and Off. It is a box with a label.  
If the check box is checked, it is represented by a tick in a box. A check box 
can be used to show/hide splashscreen at startup, toggle visibility of a toolbar etc.
</p>

<pre class="code">
package zetcode;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class CheckBoxExample extends JFrame
        implements ActionListener {

    public CheckBoxExample() {
        initUI();
    }

    public final void initUI() {

        setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
        add(Box.createRigidArea(new Dimension(15, 20)));

        JCheckBox checkbox = new JCheckBox("Show Title", true);
        checkbox.setFocusable(false);
        checkbox.addActionListener(this);
        add(checkbox);

        setSize(280, 200);
        setTitle("JCheckBox example");
        setLocationRelativeTo(null);
        setResizable(false);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public void actionPerformed(ActionEvent e) {

        JCheckBox source = (JCheckBox) e.getSource();
        boolean state = source.isSelected();

        if (state) {
            this.setTitle("JCheckbox example");
        } else {
            this.setTitle("");
        }

    }

    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                CheckBoxExample ex = new CheckBoxExample();
                ex.setVisible(true);
            }
        });

    }
}
</pre>

<p>
Our code example shows or hides the title of the window depending on its state. 
</p>

<pre class="explanation">
setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
add(Box.createRigidArea(new Dimension(15, 20)));
</pre>

<p>
In this example, we use a <code>BoxLayout</code> layout manager. 
We put some space there, so that
the checkbox is not too close to the corner.
</p>

<pre class="explanation">
JCheckBox checkbox = new JCheckBox("Show Title", true);
</pre>

<p>
Here we have a constructor for the checkbox. We provide text and state. 
</p>

<pre class="explanation">
checkbox.setFocusable(false);
</pre>

<p>
We have disabled the focus for the checkbox. A <code>JCheckBox</code> that has 
a focus may be selected or unselected with a spacebar. 
</p>

<pre class="explanation">
JCheckBox source = (JCheckBox) e.getSource();
boolean state = source.isSelected();

if (state) {
    this.setTitle("JCheckbox example");
} else {
    this.setTitle("");
}
</pre>

<p>
From the event object, we get the source component. In our case
is the a check box. We find out the selection state of the check box.
Depending on the state of the check box, we show or hide the title of the 
window. 
</p>

<img src="/img/gui/javaswing/jcheckbox.png" alt="JCheckBox">
<div class="figure">Figure: JCheckBox</div>


<h2>JSlider</h2>

<p>
JSlider is a component that lets the user graphically select a 
value by sliding a knob within a bounded interval.
Our example will show a volume control. 
</p>

<pre class="code">
package zetcode;

import java.awt.BorderLayout;
import java.awt.Dimension;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;


public class SliderExample extends JFrame {

    private JSlider slider;
    private JLabel label;

    ImageIcon mute = new ImageIcon(getClass().getResource("mute.png"));
    ImageIcon min = new ImageIcon(getClass().getResource("min.png"));
    ImageIcon med = new ImageIcon(getClass().getResource("med.png"));
    ImageIcon max = new ImageIcon(getClass().getResource("max.png"));

    public SliderExample() {
        initUI();
    }

    public final void initUI() {
        
        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
        panel.setBorder(BorderFactory.createEmptyBorder(40, 40, 40, 40));
        setLayout(new BorderLayout());

        panel.add(Box.createHorizontalGlue());
        slider = new JSlider(0, 150, 0);

        slider.setPreferredSize(new Dimension(150, 30));

        slider.addChangeListener(new ChangeListener() {
            public void stateChanged(ChangeEvent event) {
                int value = slider.getValue();
                if (value == 0) {
                    label.setIcon(mute);
                } else if (value > 0 &amp;&amp; value <= 30) {
                    label.setIcon(min);
                } else if (value > 30 &amp;&amp; value < 80) {
                    label.setIcon(med);
                } else {
                    label.setIcon(max);
                }
            }
        });

        panel.add(slider);
        panel.add(Box.createRigidArea(new Dimension(5, 0)));

        label = new JLabel(mute, JLabel.CENTER);
        panel.add(label);
        panel.add(Box.createHorizontalGlue());
        add(panel, BorderLayout.CENTER);

        pack();
        
        setTitle("JSlider");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
    }

    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                SliderExample ex = new SliderExample();
                ex.setVisible(true);
            }
        });
    }
}
</pre>

<p>
In the code example, we show a <code>JSlider</code> 
and a <code>JLabel</code>.
By dragging the slider, we change the icon on the label component. 
</p>


<pre class="explanation">
ImageIcon mute = new ImageIcon(getClass().getResource("mute.png"));
</pre>

<p>
Here we create an image icon. 
</p>

<pre class="explanation">
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
</pre>

<p>
Panel component has a horizontal <code>BoxLayout</code>.
</p>

<pre class="explanation">
panel.setBorder(BorderFactory.createEmptyBorder(40, 40, 40, 40));
</pre>

<p>
We creare a 40px border around the panel.
</p>


<pre class="explanation">
panel.add(Box.createHorizontalGlue());
</pre>

<p>
We put resizable space to bo both sides, left and right. It is to 
prevent <code>JSlider</code> from 
growing to unnatural sizes.
</p>

<pre class="explanation">
slider = new JSlider(0, 150, 0);
</pre>

<p>
This is a <code>JSlider</code> constructor. The parameters are minimum 
value, maximum value and current value.
</p>

<pre class="explanation">
slider.addChangeListener(new ChangeListener() {
...
});
</pre>

<p>
We add a <code>ChangeListener</code> to the slider. 
Inside the listener, we determine the current
slider value and update the label accordingly.
</p>

<pre class="explanation">
panel.add(Box.createRigidArea(new Dimension(5, 0)));
</pre>

<p>
We place a 5px rigid space between the two components. They are too close 
to each other, when the slider is at the end position. 
</p>

<img src="/img/gui/javaswing/jslider.png" alt="JSlider">
<div class="figure">Figure: JSlider</div>


<h2>JComboBox</h2>

<p>
Combobox is a component that combines a button or editable field and a drop-down 
list. The user can select a value from the drop-down list, which appears at the 
user's request. If you make the combo box editable, then the combo box includes 
an editable field into which the user can type a value.
</p>

<pre class="code">
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.border.LineBorder;


public class ComboBox extends JDialog implements 
		ActionListener, ItemListener {

    final String[] authors = {
	"Leo Tolstoy", "John Galsworthy", 
        "Honore de Balzac", "Stefan Zweig", 
	"Boris Pasternak", "Tom Wolfe"
    };

    final String[] images = {
	"tolstoy.jpg", "galsworthy.jpg", "balzac.jpg", 
        "zweig.jpg", "pasternak.jpg", "wolfe.jpg"
    };

    private JLabel display = null;  
    private JComboBox combobox = null;
    private JButton button = null;

    ImageIcon icon = new ImageIcon(
		ClassLoader.getSystemResource("balzac.jpg"));

    public ComboBox() {

        setLayout(new BoxLayout(getContentPane(), 
		BoxLayout.Y_AXIS));
        add(Box.createRigidArea(new Dimension(0, 35)));

        display = new JLabel();
        display.setPreferredSize(new Dimension(100, 127));
        display.setMaximumSize(new Dimension(100, 127));
        display.setAlignmentX(Component.CENTER_ALIGNMENT);
        display.setBorder(LineBorder.createGrayLineBorder());
        add(display);

        add(Box.createRigidArea(new Dimension(0, 15)));

        combobox = new JComboBox(authors);
        combobox.setSelectedIndex(-1);
        combobox.setPreferredSize(new Dimension(140, 22));
        combobox.setMaximumSize(new Dimension(140, 22));
        combobox.addItemListener(this);
        add(combobox);

        add(Box.createRigidArea(new Dimension(0, 15)));

        button = new JButton("Close");
        button.setAlignmentX(Component.CENTER_ALIGNMENT);
        button.addActionListener(this);
        add(button);

        setTitle("JComboBox");
        setSize(300, 300);
        setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        setLocationRelativeTo(null);
        setVisible(true);
    }

    public static void main(String[] args) {
        new ComboBox();
    }


    public void actionPerformed(ActionEvent e) {
        System.exit(0);
    }

    public void itemStateChanged(ItemEvent e) {

        if (e.getStateChange() == ItemEvent.SELECTED) {
            JComboBox combo = (JComboBox) e.getSource();
            int index = combo.getSelectedIndex();
            display.setIcon(new ImageIcon(
                ClassLoader.getSystemResource(images[index])));
        }

    }
}
</pre>

<p>
In our example, we have three components. A label, a combobox and a 
button. The button closes the window. We have six names of famous
 novelists in our combobox. If we select a name, an image is displayed in the label.
</p>


<pre class="explanation">
public class ComboBox extends JDialog implements 
        ActionListener, ItemListener {
</pre>

<p>
This is a dialog based application example.
</p>


<pre class="explanation">
display = new JLabel();
</pre>

<p>
The display area is a simple <code>JLabel</code>.
</p>

<pre class="explanation">
combobox = new JComboBox(authors);
combobox.setSelectedIndex(-1);
</pre>

<p>
The constructor of the <code>JComboBox</code> takes a string array of 
novelists. If we provide -1 as an argument in the <code>setSelectedIndex()</code> 
method, no item to be selected.
</p>

<pre class="explanation">
combobox.addItemListener(this);
</pre>

<p>
We add an <code>ItemListener</code> to our combobox. In the event 
handler, we get the selected index of the combobox and set an 
appropriate icon for the label. The selected item is an index to the array of images.
</p>

<!--<pre class="explanation">

</pre>

<p>

</p>-->

<img src="/img/gui/javaswing/combobox.jpg" alt="JComboBox">
<div class="figure">Figure: JComboBox</div>


<h2>JProgressBar</h2>

<p>
A progress bar is a widget that is used, when we process lengthy tasks. 
It is animated so that the user knows, that our task is progressing. The 
<code>JProgressBar</code> widget provides a horizontal or 
vertical progress bar.
The initial and minimum values are 0, and the maximum is 100.
</p>

<pre class="code">
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.Timer;


public class ProgressBar extends JFrame {

    ActionListener updateProBar;
    Timer timer;
    JProgressBar progressBar;
    JButton button;

    public ProgressBar() {

        setTitle("JProgressBar");

        JPanel panel = new JPanel();
        panel.setBorder(BorderFactory.createEmptyBorder(40, 40, 40, 40));
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));



        progressBar = new JProgressBar();

        progressBar.setMaximumSize(new Dimension(150, 20));
        progressBar.setMinimumSize(new Dimension(150, 20));
        progressBar.setPreferredSize(new Dimension(150, 20));

        progressBar.setAlignmentX(0f);

        panel.add(progressBar);
        panel.add(Box.createRigidArea(new Dimension(0, 20)));

        button = new JButton("Start");
        button.setFocusable(false);
        button.setMaximumSize(button.getPreferredSize());

        updateProBar = new ActionListener() {
            public void actionPerformed(ActionEvent actionEvent) {
                int val = progressBar.getValue();
                if (val >= 100) {
                    timer.stop();
                    button.setText("End");
                    return;
                }

                progressBar.setValue(++val);
            }
        };

        timer = new Timer(50, updateProBar);

        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (timer.isRunning()) {
                    timer.stop();
                    button.setText("Start");

                } else if (button.getText() != "End") {
                    timer.start();
                    button.setText("Stop");
                }

            }
        });


        panel.add(button);
        add(panel);

        pack();
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setResizable(false);
        setLocationRelativeTo(null);
        setVisible(true);

    }

    public static void main(String[] args) {

        new ProgressBar();
    }
}
</pre>


<p>
The example displays a progress bar and a button. The button starts and stops the progress. 
</p>

<pre class="explanation">
progressBar = new JProgressBar();
</pre>

<p>
Here we create the <code>JProgressBar</code>. The minimum 
value is 0, maximum 100 and the initial value is 0.
These are the default values.
</p>

<pre class="explanation">
progressBar.setMaximumSize(new Dimension(150, 20));
progressBar.setMinimumSize(new Dimension(150, 20));
progressBar.setPreferredSize(new Dimension(150, 20));
</pre>

<p>
These lines are for design purposes only. I want my examples to look nice. 
The default height on my box was only 14px
which looked bad.
</p>

<pre class="explanation">
progressBar.setAlignmentX(0f);
</pre>

<p>
This line aligns both progress bar with the button. To the left.
</p>


<pre class="explanation">
panel.add(Box.createRigidArea(new Dimension(0, 20)));
</pre>

<p>
Here we put some rigid space between the two components.
</p>

<pre class="explanation">
button.setFocusable(false);
</pre>

<p>
Focus looks bad, better disable it.
</p>

<pre class="explanation">
timer = new Timer(50, updateProBar);
</pre>

<p>
The timer object launches updateProBar listener every 50ms. Inside that 
listener,  we check, if the progress bar reached
the value 100 and stop the timer, or update the progress bar.
</p>

<pre class="explanation">
if (timer.isRunning()) {
    timer.stop();
    button.setText("Start");

} else if (button.getText() != "End") {
    timer.start();
    button.setText("Stop");
}
</pre>

<p>
Clicking on the button starts or stops the progress. The text of the button is 
updated dynamically. It can have Start, Stop or End String values. 
</p>

<img src="/img/gui/javaswing/progressbar.jpg" alt="JProgressBar">
<div class="figure">Figure: JProgressBar</div>


<h2>JToggleButton</h2>

<p>
<code>JToggleButton</code> is a button that has two states. 
Pressed and not pressed. You toggle between these two states by clicking on it. 
There are situations where this functionality fits well.
</p>

<pre class="code">
package zetcode;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JToggleButton;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;


public class ToggleButtonExample extends JDialog
        implements ActionListener {

    private JToggleButton redButton;
    private JToggleButton greenButton;
    private JToggleButton blueButton;
    private JPanel display;

    public ToggleButtonExample() {

        initUI();
    }

    public final void initUI() {

        JPanel bottom = new JPanel();
        bottom.setLayout(new BoxLayout(bottom, BoxLayout.X_AXIS));
        bottom.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        JPanel leftPanel = new JPanel();
        leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.Y_AXIS));

        redButton = new JToggleButton("red");
        redButton.addActionListener(this);

        greenButton = new JToggleButton("green");
        greenButton.addActionListener(this);

        blueButton = new JToggleButton("blue");
        blueButton.addActionListener(this);

        blueButton.setMaximumSize(greenButton.getMaximumSize());
        redButton.setMaximumSize(greenButton.getMaximumSize());

        leftPanel.add(redButton);
        leftPanel.add(Box.createRigidArea(new Dimension(25, 7)));
        leftPanel.add(greenButton
                );
        leftPanel.add(Box.createRigidArea(new Dimension(25, 7)));
        leftPanel.add(blueButton);


        bottom.add(leftPanel);
        bottom.add(Box.createRigidArea(new Dimension(20, 0)));

        display = new JPanel();
        display.setPreferredSize(new Dimension(110, 110));
        display.setBorder(LineBorder.createGrayLineBorder());
        display.setBackground(Color.black);

        bottom.add(display);
        add(bottom);

        pack();
        
        setTitle("JToggleButton");
        setResizable(false);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
    }

    public void actionPerformed(ActionEvent e) {

        Color color = display.getBackground();
        int red = color.getRed();
        int green = color.getGreen();
        int blue = color.getBlue();

        if (e.getActionCommand().equals("red")) {
            if (red == 0) {
                red = 255;
            } else {
                red = 0;
            }
        }

        if (e.getActionCommand().equals("green")) {
            if (green == 0) {
                green = 255;
            } else {
                green = 0;
            }
        }

        if (e.getActionCommand().equals("blue")) {
            if (blue == 0) {
                blue = 255;
            } else {
                blue = 0;
            }
        }

        Color setCol = new Color(red, green, blue);
        display.setBackground(setCol);
    }


    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                ToggleButtonExample ex = new ToggleButtonExample();
                ex.setVisible(true);
            }
        });
    }
}
</pre>


<p>
The example has three panels and three toggle buttons. Panels are bottom panel, 
left panel and display panel. The bottom panel is use to organize the left and 
display panels. For this, we use horizontal <code>BoxLayout</code> manager.
The left panel will holt three toggle buttons. This time we use vertical 
<code>BoxLayout</code> manager.
We set the background color of the display panel to black. The toggle buttons 
will toggle the red, green and blue parts of the color value. The background 
color will depend on which togglebuttons we have pressed.
</p>


<pre class="explanation">
redButton = new JToggleButton("red");
redButton.addActionListener(this);
</pre>

<p>
Here we create a toggle button and set an action listener to it. 
</p>

<pre class="explanation">
blueButton.setMaximumSize(greenButton.getMaximumSize());
redButton.setMaximumSize(greenButton.getMaximumSize());
</pre>

<p>
We make all three buttons of equal size. 
</p>


<pre class="explanation">
Color color = display.getBackground();
int red = color.getRed();
int green = color.getGreen();
int blue = color.getBlue();
</pre>

<p>
In the <code>actionPerformed</code> method, we determine the current red, green, blue parts of the
display background color.
</p>

<pre class="explanation">
if (e.getActionCommand().equals("red")) {
    if (red == 0) {
        red = 255;
    } else {
        red = 0;
    }
}
</pre>

<p>
We determine, which button was toggled, and update the color part of the RGB value accordingly.
</p>

<pre class="explanation">
Color setCol = new Color(red, green, blue);
display.setBackground(setCol);
</pre>

<p>
Here a new color is created and the display panel is updated to a new color.
</p>

<img src="/img/gui/javaswing/jtogglebutton.png" alt="JToggleButton">
<div class="figure">Figure: JToggleButton</div>


<p>
In this part of the Java Swing tutorial, we have covered
basic Swing components. 
</p>


<div class="center"> 
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* horizontal */
google_ad_slot = "1734478269";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 
</div>
<br>


<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡ 
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>


<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified December 13, 2010  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>

